<?php
    $slug = $_GET["id"];
    $do = $_GET['do'];
    $id = $_GET['userID'];
    $num = $_GET['num'];
    $conn = mysqli_connect("localhost", "root", "123456", "sbeam");
    $flag = false;
    $result = mysqli_query($conn, "SELECT * FROM cart where id='$id'");
    // 判断有没有查询到内容
    // $info = mysqli_num_rows($result);
    $info = mysqli_fetch_assoc($result);
    $arr = json_decode($info['cart'],true);

    switch($do){
        case 'del':
            foreach($arr as $k=>$v){
            // 套娃 k是数组下标 v是对象 v的[]才是标题
            if($v['slug'] == $slug){
                unset($arr[$k]);
                // 用完unset（）过后一定要用array_values（）重组数组！！！
                $arr = array_values($arr);
                $flag = true;
                break;
                }
            }
            break;
        case 'increase':
        case 'decrease':
            foreach($arr as $k=>$v){
                // 套娃 k是数组下标 v是对象 v的[]才是标题
                if($v['slug'] == $slug){
                    $v['num'] = $num ;
                    $arr[$k] = $v;
                    $flag = true;
                    break;
                    }
                }
            break;
    }

    
    //    arr转json字符串
    $data = json_encode($arr);
    //    送入数据库 
    mysqli_query($conn,"update cart set cart = '$data' where id = $id;");
    if(!$flag){
        echo json_encode(array("error" => 0, "data" => "操作成功"));
    }else{
        echo json_encode(array("error" => 1, "data" => "操作失败"));
    }
?>